package com.mingqijia.gassafety.webserver.service.workorder.impl;
import static com.mingqijia.gassafety.shared.constant.Constants.BIND_CHANNEL_ASST;
import static com.mingqijia.gassafety.shared.constant.Constants.BIND_CHANNEL_MBP;
import static com.mingqijia.gassafety.shared.constant.Constants.IS_DELETED_FALSE;
import static com.mingqijia.gassafety.shared.constant.Constants.TCIS_CONTACTS_UPDATE;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.validation.Valid;

import com.mingqijia.gassafety.db.mapper.DictionaryMapper;
import com.mingqijia.gassafety.shared.constant.CustTypeEnum;
import com.mingqijia.gassafety.webserver.request.workorder.asst.ContactsItemRequest;
import org.apache.commons.collections.MapUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.LocationUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gap.basic.exception.BizException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.Consumer;
import com.mingqijia.gassafety.db.entity.ConsumerDtuHistory;
import com.mingqijia.gassafety.db.entity.Contacts;
import com.mingqijia.gassafety.db.entity.Department;
import com.mingqijia.gassafety.db.entity.Dictionary;
import com.mingqijia.gassafety.db.entity.Dtu;
import com.mingqijia.gassafety.db.entity.DtuAep;
import com.mingqijia.gassafety.db.entity.HistoryBroken;
import com.mingqijia.gassafety.db.entity.WarningAlarm;
import com.mingqijia.gassafety.db.entity.WorkOrderHistory;
import com.mingqijia.gassafety.db.entity.vo.DeviceStateVO;
import com.mingqijia.gassafety.db.entity.vo.HistoryAlarmVo;
import com.mingqijia.gassafety.db.entity.vo.LatestLogListVO;
import com.mingqijia.gassafety.db.mapper.ConsumerDtuHistoryMapper;
import com.mingqijia.gassafety.db.mapper.ContactsMapper;
import com.mingqijia.gassafety.db.mapper.DepartmentMapper;
import com.mingqijia.gassafety.db.mapper.DtuMapper;
import com.mingqijia.gassafety.db.mapper.HistoryAlarmMapper;
import com.mingqijia.gassafety.shared.constant.AsstConstants;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.CustStatusEnum;
import com.mingqijia.gassafety.shared.constant.EquipmentStatusEnum;
import com.mingqijia.gassafety.shared.constant.EquipmentType;
import com.mingqijia.gassafety.shared.constant.PhoneTypeEnum;
import com.mingqijia.gassafety.shared.constant.TemplateTypeEnum;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.shared.utils.commonUtils.SnowflakeUtil;
import com.mingqijia.gassafety.webserver.request.BindingPositionRequest;
import com.mingqijia.gassafety.webserver.request.ConsumerBindingRequest;
import com.mingqijia.gassafety.webserver.request.ConsumerunBindingRequest;
import com.mingqijia.gassafety.webserver.request.ContactsRequest;
import com.mingqijia.gassafety.webserver.request.NewAsstCreateRequest;
import com.mingqijia.gassafety.webserver.request.NewAsstUnbindRequest;
import com.mingqijia.gassafety.webserver.request.workorder.NewAsstEditContactRequest;
import com.mingqijia.gassafety.webserver.request.workorder.SparkOrderRequest;
import com.mingqijia.gassafety.webserver.request.workorder.SparkOrderStatusRequest;
import com.mingqijia.gassafety.webserver.request.workorder.mbp.EquipmentInfoRequest;
import com.mingqijia.gassafety.webserver.response.VccUserRseponse;
import com.mingqijia.gassafety.webserver.response.workorder.mbp.BrokenLogResponse;
import com.mingqijia.gassafety.webserver.response.workorder.mbp.InfoAndAlertLogResponse;
import com.mingqijia.gassafety.webserver.service.ConsumerLocationService;
import com.mingqijia.gassafety.webserver.service.ConsumerService;
import com.mingqijia.gassafety.webserver.service.ConsumerServiceInfoService;
import com.mingqijia.gassafety.webserver.service.ContactsService;
import com.mingqijia.gassafety.webserver.service.DeviceStateService;
import com.mingqijia.gassafety.webserver.service.DictionaryService;
import com.mingqijia.gassafety.webserver.service.DtuAepService;
import com.mingqijia.gassafety.webserver.service.EquipmentService;
import com.mingqijia.gassafety.webserver.service.HistoryBrokenService;
import com.mingqijia.gassafety.webserver.service.workorder.SyncNewAsstOrderService;
import com.mingqijia.gassafety.webserver.service.workorder.WorkOrderHistoryService;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import lombok.extern.slf4j.Slf4j;

import static com.mingqijia.gassafety.shared.constant.Constants.BIND_CHANNEL_TCIS_REFUND;

/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName SyncNewAsstOrderServiceImpl.java
 * @Description TODO
 * @createTime 2023年10月20日
 */
@Service
@Slf4j
public class SyncNewAsstOrderServiceImpl implements SyncNewAsstOrderService {
    private static final String CUST_TYPE_ENUM = "cust_type_enum";

    @Autowired
    private ConsumerService consumerService;
    @Autowired
    private ConsumerServiceInfoService consumerServiceInfoService;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private WorkOrderHistoryService workOrderHistoryService;
    @Autowired
    private DtuAepService dtuAepService;
    @Autowired
    private HistoryAlarmMapper historyAlarmMapper;
    @Autowired
    private HistoryBrokenService brokenService;
    @Autowired
    private DeviceStateService stateService;
    @Autowired
    private ContactsMapper contactsMapper;
    @Autowired
    private ContactsService contactsService;
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private ConsumerDtuHistoryMapper consumerDtuHistoryMapper;
    @Autowired
    private DtuMapper dtuMapper;
    @Autowired
    private ConfigureHolder holder;
    @Autowired
    ConsumerLocationService consumerLocationService;

    @Autowired
    DictionaryMapper dictionaryMapper;

    private static final String phoneRegex = "^(1[3-9])\\d{9}$";
    private static final String landlineRegex = "\\d{3,4}[-]\\d{7,8}";

    private static final String commonRegex = "\\d{1,20}";
    @Autowired
    private LocationUtil locationUtil;


    public Map<String,String> queryDictMapByCodeNoSpId(String dictCode, Map<String,String> defaultMap) {
        Map<String,String> map = new HashMap<>();
        QueryWrapper<Dictionary> dictionaryQueryWrapper = new QueryWrapper<>();
        dictionaryQueryWrapper.lambda()
                .eq(Dictionary::getIsDeleted, IS_DELETED_FALSE)
                .eq(Dictionary::getSpId, "0")
                .eq(Dictionary::getDictCode, dictCode);
        List<Dictionary> dictionaryList = dictionaryMapper.selectList(dictionaryQueryWrapper);
        if (CollectionUtil.isNotEmpty(dictionaryList)) {
            map = dictionaryList.stream().collect(Collectors.toMap(Dictionary::getValue, Dictionary::getAlias,(k1,k2)->k2));
        }
        else {
            map = defaultMap;
        }
        if (MapUtils.isEmpty(map)) map = defaultMap;
        return map;
    }

    /**
     * 新时刻助手绑定
     *
     * @param request
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createConsumerBindImei( NewAsstCreateRequest request) {
        log.info("createConsumerBindImei-param：{}",JSONObject.toJSONString(request));
        Dictionary dictionary =mbpOrgMapping(request.getOrgCode());
        String spId =dictionary.getValue();
        VccUserRseponse vccUser = consumerService.getVccUser(request.getSubsCode(),spId,"");
        if (vccUser==null)    throw  new BizException("户号:"+request.getSubsCode()+"vcc未查到");

        //判断该 用户id是否存在
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Consumer::getSubsCode, request.getSubsCode())
                .eq(Consumer::getIsDeleted, IS_DELETED_FALSE)
                .eq(Consumer::getSpId, spId);
        List<Consumer> consumers = consumerService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(consumers)&&consumers.size()>1){
            log.info("新时刻助手绑定,一个户号存在多个客户:{}", JSONObject.toJSONString(consumers));
            return;
        }
        Consumer consumer = CollectionUtil.isNotEmpty(consumers) ? consumers.get(0) : null;
        String alias = dictionary.getAlias();
        String orgCode="";
        if (!StringUtils.isEmpty(alias)&&alias.contains("|")) {
            String[] split = alias.split("\\|");
            if (split.length>0)orgCode= split[split.length-1];
        }
        LambdaQueryWrapper<Dtu> dtuQuery = new LambdaQueryWrapper<>();
        dtuQuery.or().eq(Dtu::getIsDeleted,0).eq(Dtu::getIMEI,request.getImei())
                .eq(Dtu::getSpId,spId);
        List<Dtu> dtus = dtuMapper.selectList(dtuQuery);
        if (CollectionUtils.isEmpty(dtus)) throw  new BizException("设备不存在");
        if (request.getType() == 1){
            //置换设备--绑定
            if (consumer == null)throw new BizException("当前户号下不存在客户");
            equipmentService.deviceSuitable(request.getImei());
            log.info("deviceSuitable-info:{}",request.getImei()+":可以进行置换");
            //置换
            LambdaQueryWrapper<WorkOrderHistory> query = new LambdaQueryWrapper<>();
            query.or().eq(WorkOrderHistory::getIsDeleted,0).eq(WorkOrderHistory::getHandleStatus,0)
                    .eq(WorkOrderHistory::getOrderNo,request.getOrderNo());
            List<WorkOrderHistory> list = workOrderHistoryService.list(query);
            log.info("createConsumerBindImei-list:{}",JSONObject.toJSON(list));
            if (CollectionUtils.isEmpty(list)) throw new BizException("工单不存在或已完工");
            WorkOrderHistory workOrderHistory = list.get(0);
            log.info("createConsumerBindImei-new：{}，old：{}", request.getImei(), workOrderHistory.getDeviceId());
            if (workOrderHistory.getDeviceId().equals(request.getImei())) throw new BizException("老设备与新设备相同");
            consumerDtuHistory(workOrderHistory.getPkid(), request.getImei(),workOrderHistory.getDeviceId(), 1, consumer.getId(), spId, consumer.getIndustryType());
            workOrderHistory.setNewDeviceId(request.getImei());
            workOrderHistoryService.updateById(workOrderHistory);
            Dtu deviceByImei = equipmentService.getDeviceByImei(workOrderHistory.getDeviceId(), workOrderHistory.getSpId());
            String imei = deviceByImei.getIMEI();
            if (imei.contains("-")) {
                String[] imeis = imei.split("-");
                imei = imeis[0];
            }
            LambdaUpdateWrapper<Dtu> old = new LambdaUpdateWrapper<>();
            old.eq(Dtu::getParentImei, imei)
                    .eq(Dtu::getSpId, spId).eq(Dtu::getIsDeleted, IS_DELETED_FALSE)
                    .set(Dtu::getConsumerId, 0)
                    .set(Dtu::getSectorType, Constants.BLANK);
            equipmentService.update(old);
            String requestImei = request.getImei();
            if (requestImei.contains("-")) {
                String[] imeis = requestImei.split("-");
                requestImei = imeis[0];
            }
            LambdaUpdateWrapper<Dtu> lqw = new LambdaUpdateWrapper<>();
            lqw.eq(Dtu::getParentImei, requestImei)
                    .eq(Dtu::getSpId, spId).eq(Dtu::getIsDeleted, IS_DELETED_FALSE)
                    .set(Dtu::getConsumerId, consumer.getId())
                    .set(Dtu::getSectorType, StringUtils.isEmpty(consumer.getIndustryType()) ? Constants.BLANK : consumer.getIndustryType())
            .set(Dtu::getInstallationPosition,deviceByImei.getInstallationPosition())
            .set(Dtu::getInstallationAddress,consumer.getCustAddress())
            .set(Dtu::getPositionLat,consumer.getPositionLat())
            .set(Dtu::getPositionLon,consumer.getPositionLon())
            .set(Dtu::getSource,deviceByImei.getSource())
            ;
            equipmentService.update(lqw);

            consumerLocationService.updateConsumerLocationDeviceNum(consumer.getSpId(),consumer.getId());
            return;
        }else if (null!=consumer && null!=dtus.get(0).getConsumerId()
                && consumer.getId().equals(dtus.get(0).getConsumerId())){
            log.info("客户:{}已经绑定设备:{}",consumer.getId(),request.getImei());
            return;
        }
        double positionLat=0;
        double positionLon=0;
        String adcode ="";
        if (!StringUtils.isEmpty(request.getPositionLong())&&!StringUtils.isEmpty(request.getPositionLat())){
            positionLat = new BigDecimal(request.getPositionLat()).setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
            positionLon = new BigDecimal(request.getPositionLong()).setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
        }else {
            double[] latLng = locationUtil.baiDuUrlGeocoding(dictionary.getDescription()+vccUser.getCustAddress());
            positionLat = latLng[0];
            positionLon = latLng[1];
        }
        if (consumer != null) {
                Consumer consumerNew = new Consumer();
                consumerNew.setIsDeleted(false);
                consumerNew.setId(consumer.getId());
                consumerNew.setCreatedAt(new Date());
                consumerNew.setPositionLat(positionLat);
                consumerNew.setPositionLon(positionLon);
                consumerNew.setAdCode(adcode);
                consumerNew.setCustType(queryDictMapByCodeNoSpId(CUST_TYPE_ENUM , CustTypeEnum.toMap()).get(vccUser.getCustType()));
                consumerNew.setCustTypeCode(vccUser.getCustType());
                consumerNew.setCustStatus(CustStatusEnum.getCustStatusName(vccUser.getCustStatus()));
                consumerNew.setStatus(1);
                consumerNew.setOrgCode(orgCode);
                consumerService.updateById(consumerNew);
        } else {
            // 用户不存在,创建对应客户
            QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
            departmentQueryWrapper.lambda().eq(Department::getSpId, spId);
            Department department = departmentMapper.selectOne(departmentQueryWrapper);
            Consumer consumerAdd = new Consumer();
            consumerAdd.setName("");
            consumerAdd.setDepartmentId(department.getId() );
            consumerAdd.setPath( department.getPath() );
            consumerAdd.setTemplateType(BIND_CHANNEL_ASST);
            consumerAdd.setSubsCode(request.getSubsCode());
            consumerAdd.setSource(1);
            if (!StringUtils.isEmpty(request.getPhone())) {
                consumerAdd.setPhone(request.getPhone());
            }
            consumerAdd.setName(request.getName());
            consumerAdd.setIndustryType("notFilled");
            consumerAdd.setSpId(spId);
            consumerAdd.setStatusAnyalert(false);
            consumerAdd.setStatusAnybroken(false);
            consumerAdd.setStatusAnyoffline(false);
            consumerAdd.setStatusAnynormal(true);
            consumerAdd.setStatusUpdatetime(new Date());
            consumerAdd.setCustName(vccUser.getCustName());
            consumerAdd.setCustAddress(vccUser.getCustAddress());
            consumerAdd.setCustPhone(vccUser.getCustPhone());
            consumerAdd.setPositionLat(positionLat);
            consumerAdd.setPositionLon(positionLon);
            consumerAdd.setStatus(1);
            consumerAdd.setAdCode(adcode);
            consumerAdd.setCustType(queryDictMapByCodeNoSpId(CUST_TYPE_ENUM , CustTypeEnum.toMap()).get(vccUser.getCustType()));
            consumerAdd.setCustTypeCode(vccUser.getCustType());
            consumerAdd.setCustStatus(CustStatusEnum.getCustStatusName(vccUser.getCustStatus()));
            consumerAdd.setOrgCode(orgCode);
            consumerService.save(consumerAdd);
        }

        //获取客户id
        queryWrapper.lambda().eq(Consumer::getIsDeleted, false);
        Consumer consumerNow = consumerService.getOne(queryWrapper);
        log.info("客户id:{}", consumerNow.getId());
        consumerLocationService.updateConsumerLocation(consumerNow);
        // 修改联系人
        NewAsstEditContactRequest contact = new NewAsstEditContactRequest();
        contact.setSubsCode(request.getSubsCode());
        contact.setDataOrgId(request.getOrgCode());
        List<ContactsRequest> contactPhoneList = new ArrayList<>();
        contact.setContactsList(contactPhoneList);
        if (!StringUtils.isEmpty(request.getPhone())) {
            ContactsRequest req = new ContactsRequest();
            req.setName(request.getName());
            req.setTelephone(request.getPhone());
            req.setRemark(PhoneTypeEnum.TYPE_0.getCode());
            contactPhoneList.add(req);
        }
        if (!StringUtils.isEmpty(request.getSparePhone())) {
            String[] sparePhones = request.getSparePhone().split(Constants.STR_COMMA);
            Integer number = 1;
            for (String sparePhone : sparePhones) {
                ContactsRequest req = new ContactsRequest();
                req.setName(request.getName());
                req.setTelephone(sparePhone);
                req.setRemark("asst_" + number);
                number++;
                contactPhoneList.add(req);
            }
        }
        this.editContacts(contact);

        //构建入参
        ConsumerBindingRequest bindingRequest = new ConsumerBindingRequest();
        List<BindingPositionRequest> list = new ArrayList<>();
        BindingPositionRequest bindingPositionRequest = new BindingPositionRequest();
        bindingPositionRequest.setImei(request.getImei());
        list.add(bindingPositionRequest);

        bindingRequest.setConsumerId(consumerNow.getId());
        bindingRequest.setImeiList(list);
        bindingRequest.setBindChannel(BIND_CHANNEL_MBP);
        bindingRequest.setOutOrderCode(request.getPkid());
        bindingRequest.setSpId(spId);
        bindingRequest.setSource(1);
        bindingRequest.setAddress(vccUser.getCustAddress());
        bindingRequest.setPositionLat(positionLat);
        bindingRequest.setPositionLon(positionLon);
        log.info("createConsumerBindImei-bindingRequest :{}", JSONObject.toJSONString(bindingRequest));
        bindingRequest.setIsUpdate(1);
        consumerService.bindingEquipment(bindingRequest);
        //新增工单记录
        WorkOrderHistory workOrderHistory = new WorkOrderHistory();
        workOrderHistory.setDeviceId(request.getImei());
        workOrderHistory.setOrderNo(request.getOrderNo());
        workOrderHistory.setFromSystem(AsstConstants.FROM_SYSTEM_2);
        workOrderHistory.setSpId(spId);
        workOrderHistory.setOrderType(1);
        workOrderHistory.setFromSystem(2);
        workOrderHistory.setPkid(request.getPkid());
        workOrderHistory.setSubsCode(request.getSubsCode());
        workOrderHistory.setWorkSystem(1);
        workOrderHistory.setOrderChannel(1);
        String woSeq = workOrderHistoryService.WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId();
        workOrderHistory.setWoSeq(woSeq);
        workOrderHistoryService.insertHistory(workOrderHistory);
    }


    /**
     * 新时刻助手解绑
     *
     * @param request
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unbindEquipment(@Valid NewAsstUnbindRequest request) {
        log.info("unbindEquipment-param:{}",JSONObject.toJSONString(request));
        if( request.getType() != 3 && StringUtils.isEmpty(request.getOrderNo()) ){
            throw new BizException("工单编号不能为空");
        }
        Dictionary dictionary =mbpOrgMapping(request.getOrgCode());
        String spId =dictionary.getValue();
        LambdaQueryWrapper<Dtu> query = new LambdaQueryWrapper<>();
        query.or().eq(Dtu::getIsDeleted,0).eq(Dtu::getIMEI,request.getImei())
                .eq(Dtu::getSpId,spId);
        List<Dtu> dtus = dtuMapper.selectList(query);
        if (CollectionUtils.isEmpty(dtus)) throw  new BizException("设备不存在");
        if (request.getType() == 1){
            //置换设备--解绑
            LambdaUpdateWrapper<Dtu> lqw = new LambdaUpdateWrapper<>();
            Dtu deviceByImei = equipmentService.getDeviceByImei(request.getImei(), spId);
            if (deviceByImei==null)throw new BizException("设备不存在");
            String imei = request.getImei();
            if (imei.contains("-")) {
                imei = imei.split("-")[0];
            }
            lqw.eq(Dtu::getParentImei, imei)
                    .eq(Dtu::getSpId, spId).eq(Dtu::getIsDeleted, IS_DELETED_FALSE)
                    .set(Dtu::getConsumerId, 0)
                    .set(Dtu::getSectorType, Constants.BLANK);
            equipmentService.update(lqw);
            consumerDtuHistory("",request.getImei(),"",0,deviceByImei.getConsumerId(),spId, "");
            consumerLocationService.updateConsumerLocationDeviceNum(spId,deviceByImei.getConsumerId());
            consumerService.unbindEquipmentToTcis(request,spId);
            return;
        }
        ConsumerunBindingRequest bindingRequest = new ConsumerunBindingRequest();
        bindingRequest.setImei(request.getImei());
        bindingRequest.setOutOrderCode(request.getPkid());
        bindingRequest.setTemplateType(TemplateTypeEnum.TEMPLATE_TYPE_1.getCode());
        if (request.getType() == 3){
            bindingRequest.setBindChannel(BIND_CHANNEL_TCIS_REFUND);
        }else{
            bindingRequest.setBindChannel(BIND_CHANNEL_MBP);
        }
        //根据 用户id查询对应客户id
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        consumerQueryWrapper.lambda().eq(Consumer::getSubsCode, request.getSubsCode())
                .eq(Consumer::getSpId,spId)
                .eq(Consumer::getIsDeleted, false);
        List<Consumer> consumers = consumerService.list(consumerQueryWrapper);
        if (CollectionUtil.isNotEmpty(consumers)){
            bindingRequest.setConsumerId(consumers.get(0).getId());
        }else {
            throw  new BizException("户号:"+request.getSubsCode()+",未创建客户");
        }
        bindingRequest.setSpId(spId);
        //判断该imei设备是否存在且绑定该客户
        LambdaQueryWrapper<Dtu> dtuQueryWrapper = new LambdaQueryWrapper<>();
        dtuQueryWrapper.eq(Dtu::getIMEI, request.getImei()).eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
        .eq(Dtu::getConsumerId, bindingRequest.getConsumerId()).eq(Dtu::getSpId, spId);
        Dtu one = equipmentService.getOne(dtuQueryWrapper);
        if (one == null) {
            log.info("客户:{}已经解绑设备:{}",bindingRequest.getConsumerId(),request.getImei());
            return;
        }
        bindingRequest.setOperateType(request.getType());
        consumerService.unbindEquipment(bindingRequest);
        //解绑删除工单记录
        if (request.getType() == 3){
            workOrderHistoryService.deleteHistoryByReturn(request.getImei(), request.getSubsCode(), spId, 1);
        }else {
            workOrderHistoryService.deleteHistory(request.getOrderNo(), request.getImei(), spId);
        }
    }

    @Override
    public InfoAndAlertLogResponse getEquipmentInfo(EquipmentInfoRequest request) {
        log.info("获取设备信息和报警记录入参：{}", request);
        Dictionary dictionary =mbpOrgMapping(request.getOrgCode());
        String spId =dictionary.getValue();
        InfoAndAlertLogResponse response = new InfoAndAlertLogResponse();
        //设备类型
        LambdaQueryWrapper<Dtu> dtulqw = new LambdaQueryWrapper<>();
        dtulqw.eq(Dtu::getIMEI, request.getImei()).eq(Dtu::getIsDeleted, IS_DELETED_FALSE)
                .eq(Dtu::getSpId, spId);
        Dtu dtu = equipmentService.getOne(dtulqw);
        if (dtu == null){
            return null;
        }
        response.setIsController(EquipmentType.GAS_ALARM_CONTROLLER.getCode().equals(dtu.getEquipmentType()) ? 1:0);

        //设备注册信息
        LambdaQueryWrapper<DtuAep> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DtuAep::getIMEI, request.getImei()).eq(DtuAep::getIsDeleted, IS_DELETED_FALSE)
                .eq(DtuAep::getSpId, spId);
        DtuAep one = dtuAepService.getOne(lqw);
        if (one != null){
            BeanUtils.copyProperties(one, response);
        }
        DeviceStateVO stateVO = stateService.getDeviceStateByImei(request.getImei(), spId);
        if (stateVO != null){
            response.setDeviceStatus(stateVO.getEquipmentStatus());
            response.setDeviceStatusMsg(EquipmentStatusEnum.getEquipmentStatusMsg(stateVO.getEquipmentStatus()));
        }
        response.setImei(request.getImei());

        //设备报警记录
        LatestLogListVO vo = new LatestLogListVO();
        vo.setImei(request.getImei());
        List<String> spIds = new ArrayList<>();
        spIds.add(spId);
        vo.setSpIds(spIds);
        Page<HistoryAlarmVo> pager = PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<HistoryAlarmVo> vccRecord = historyAlarmMapper.getVccRecord(vo);
        List<InfoAndAlertLogResponse.AlertLogVO> collect = vccRecord.stream().map(item -> {
            InfoAndAlertLogResponse.AlertLogVO alertLogVO = new InfoAndAlertLogResponse.AlertLogVO();
            alertLogVO.setWarningStartTime(item.getLatestTime());
            alertLogVO.setWarningDuration(item.getWarnDuration());
            alertLogVO.setConcentration(item.getConcentration());
            return alertLogVO;
        }).collect(Collectors.toList());
        PageUtil<InfoAndAlertLogResponse.AlertLogVO> page =
                new PageUtil<>(request.getPageNum(), request.getPageSize(), pager.getTotal(), collect);
        response.setAlertLog(page);
        return response;
    }

    @Override
    public PageUtil<BrokenLogResponse> getBrokenLog(EquipmentInfoRequest request) {
        log.info("故障记录入参：{}", request);
        Dictionary dictionary =mbpOrgMapping(request.getOrgCode());
        String spId =dictionary.getValue();
        LambdaQueryWrapper<HistoryBroken> lqw = new LambdaQueryWrapper<>();
        lqw.eq(HistoryBroken::getIMEI, request.getImei()).eq(HistoryBroken::getIsDeleted, IS_DELETED_FALSE)
                .eq(HistoryBroken::getSpId, spId);
        Page<WarningAlarm> pager = PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<HistoryBroken> list = brokenService.list(lqw);
        List<BrokenLogResponse> collect = list.stream().map(item -> {
            BrokenLogResponse response = new BrokenLogResponse();
            BeanUtils.copyProperties(item, response);
            return response;
        }).collect(Collectors.toList());
        PageUtil<BrokenLogResponse> page =
                new PageUtil<>(request.getPageNum(), request.getPageSize(), pager.getTotal(), collect);
        return page;
    }

    @Override
    public void editContacts(NewAsstEditContactRequest request) {
        log.info("修改联系人入参：{}", request);
        Dictionary dictionary = mbpOrgMapping(request.getDataOrgId());
        String spId = dictionary.getValue();
        List<DictionaryItemRespDTO> dtos = holder.getDictionaryByKey(TCIS_CONTACTS_UPDATE);
        if (CollectionUtils.isEmpty(dtos)){
            throw new BizException("缺少联系人开关字典配置，请联系管理员");
        }
        boolean flag = false;
        for (DictionaryItemRespDTO dto : dtos) {
            if (spId.equals(dto.getValue())){
                flag = true;
                break;
            }
        }
        if (!flag){
            return;
        }
        LambdaQueryWrapper<Consumer> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Consumer::getSubsCode, request.getSubsCode()).eq(Consumer::getSpId, spId)
                .eq(Consumer::getIsDeleted, IS_DELETED_FALSE);
        List<Consumer> consumers = consumerService.list(lqw);
        if (CollectionUtils.isEmpty(consumers)) {
            throw new BizException("户号" + request.getSubsCode() + "在报警器系统未创建客户");
        }
        Integer consumerId = consumers.get(0).getId();
        LambdaQueryWrapper<Contacts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Contacts::getConsumerId, consumerId).eq(Contacts::getIsDeleted, IS_DELETED_FALSE);
        List<String> telephoneList = request.getContactsList().stream().map(ContactsRequest::getTelephone).collect(Collectors.toList());
        for (String telephone : telephoneList) {
            if(!StringUtils.isEmpty(telephone)){
                boolean isMatch = Pattern.matches(phoneRegex, telephone);
                boolean landlineMatch = Pattern.matches(landlineRegex, telephone);
                boolean commonMatch = Pattern.matches(commonRegex, telephone);
                if (!isMatch && !landlineMatch && !commonMatch) throw new BizException("联系方式格式存在错误");
            }
        }
        Set<String> set = new HashSet<String>();
        List<Contacts> oldContactsList = contactsMapper.selectList(queryWrapper);
        List<Contacts> requestContacts = new ArrayList<>();
        for (ContactsRequest contactsRequest : request.getContactsList()) {
            if (StringUtils.isEmpty(contactsRequest.getRemark())){
                throw new BizException("联系方式标签不能为空");
            }
            if (!StringUtils.isEmpty(contactsRequest.getTelephone()) && set.add(contactsRequest.getTelephone())){
                Contacts contacts = new Contacts();
                BeanUtils.copyProperties(contactsRequest, contacts);
                contacts.setConsumerId(consumerId);
                contacts.setLevel(1);
                contacts.setSpId(spId);
                contacts.setTag(contactsRequest.getRemark());
                contacts.setRemark(PhoneTypeEnum.matcher(contactsRequest.getRemark()).getMsg());
                requestContacts.add(contacts);

                // update by wangwei for task 10831
                // throw new BizException("联系方式不能为空");
            }
        }
        if (CollectionUtils.isEmpty(oldContactsList)) {
            //请求来的联系人全部为新增联系人
            contactsService.saveBatch(requestContacts);
            log.info("新增联系人为{}", requestContacts);
        } else {
            List<String> oldTags = oldContactsList.stream().map(Contacts::getTag).collect(Collectors.toList());
            List<String> newTags = requestContacts.stream().map(Contacts::getTag).collect(Collectors.toList());
            HashSet<String> oldSet = new HashSet<>(oldTags);
            HashSet<String> newSet = new HashSet<>(newTags);
            for (Contacts requestContact : requestContacts) {
                if (oldSet.add(requestContact.getTag())) {
                    //oldset新增成功则为新增
                    contactsService.save(requestContact);
                    log.info("新增联系人为：{}", requestContact);
                }else {
                    //否则为更新
                    LambdaUpdateWrapper<Contacts> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(Contacts::getConsumerId, consumerId)
                            .eq(Contacts::getIsDeleted, IS_DELETED_FALSE)
                            .eq(Contacts::getTag, requestContact.getTag());
                    Contacts updateContacts = new Contacts();
                    updateContacts.setTelephone(requestContact.getTelephone());
                    contactsService.update(requestContact, updateWrapper);
                    log.info("修改联系人为：{}", requestContact);
                }
            }
            for (Contacts contacts : oldContactsList) {
                if (newSet.add(contacts.getTag())){
                    //新的set中增加旧的成功则为删除
                    contacts.setIsDeleted(true);
                    contacts.setUpdatedAt(new Date());
                    contactsService.updateById(contacts);
                    log.info("删除联系人为：{}", contacts);
                }
            }

        }

    }

    /**
     * 更新联系人信息【后续延伸业务工单，mbp共用此方法】
     * @param contactsList
     * @param spId
     * @param consumer
     */
    @Override
    public void doEditContacts(List<ContactsItemRequest> contactsList, String spId, Consumer consumer){
        Integer consumerId = consumer.getId();
        List<String> telephoneList = contactsList.stream().
                map(ContactsItemRequest::getTelephone).
                collect(Collectors.toList());
        for (String telephone : telephoneList) {
            if(!StringUtils.isEmpty(telephone)){
                boolean isMatch = Pattern.matches(phoneRegex, telephone);
                boolean landlineMatch = Pattern.matches(landlineRegex, telephone);
                boolean commonMatch = Pattern.matches(commonRegex, telephone);
                if (!isMatch && !landlineMatch && !commonMatch) throw new BizException("联系方式格式存在错误");
            }
        }
        Set<String> set = new HashSet<String>();
        LambdaQueryWrapper<Contacts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Contacts::getConsumerId, consumerId)
                .eq(Contacts::getIsDeleted, IS_DELETED_FALSE);
        List<Contacts> oldContactsList = contactsMapper.selectList(queryWrapper);
        List<String> subsPhones = new ArrayList<>();
        if (null!=oldContactsList){
            subsPhones = oldContactsList.stream()
                    .filter(item->PhoneTypeEnum.TYPE_0.getCode().equals(item.getTag()))
                    .map(Contacts::getTelephone).collect(Collectors.toList());
        }
        List<Contacts> requestContacts = new ArrayList<>();
        for (ContactsItemRequest contactsRequest : contactsList) {
            if (StringUtils.isEmpty(contactsRequest.getTag())){
                throw new BizException("联系方式标签不能为空");
            }
            if (PhoneTypeEnum.TYPE_0.getCode().equals(contactsRequest.getTag())){
                throw new BizException("联系方式标签不能户主手机号");
            }
            if (!StringUtils.isEmpty(contactsRequest.getTelephone()) && set.add(contactsRequest.getTelephone()) &&
                    !subsPhones.contains(contactsRequest.getTelephone())){
                String no = StringUtils.replace(contactsRequest.getTag(),"asst_", "");
                Contacts contacts = new Contacts();
                BeanUtils.copyProperties(contactsRequest, contacts);
                contacts.setConsumerId(consumerId);
                contacts.setLevel(1);
                contacts.setSpId(spId);
                contacts.setTag(contactsRequest.getTag());
                contacts.setRemark("备用手机号"+no);
                requestContacts.add(contacts);
            }
        }
        if (CollectionUtils.isEmpty(oldContactsList)) {
            //请求来的联系人全部为新增联系人
            contactsService.saveBatch(requestContacts);
            log.info("新增联系人为{}", requestContacts);
        } else {
            List<String> oldTags = oldContactsList.stream().map(Contacts::getTag).collect(Collectors.toList());
            List<String> newTags = requestContacts.stream().map(Contacts::getTag).collect(Collectors.toList());
            HashSet<String> oldSet = new HashSet<>(oldTags);
            HashSet<String> newSet = new HashSet<>(newTags);
            for (Contacts requestContact : requestContacts) {
                if (oldSet.add(requestContact.getTag())) {
                    //oldset新增成功则为新增
                    contactsService.save(requestContact);
                    log.info("新增联系人为：{}", requestContact);
                }else {
                    //否则为更新
                    LambdaUpdateWrapper<Contacts> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(Contacts::getConsumerId, consumerId)
                            .eq(Contacts::getIsDeleted, IS_DELETED_FALSE)
                            .eq(Contacts::getTag, requestContact.getTag());
                    Contacts updateContacts = new Contacts();
                    updateContacts.setTelephone(requestContact.getTelephone());
                    updateContacts.setName(requestContact.getName());
                    contactsService.update(requestContact, updateWrapper);
                    log.info("修改联系人为：{}", requestContact);
                }
            }
            for (Contacts contacts : oldContactsList) {
                if (newSet.add(contacts.getTag()) && !PhoneTypeEnum.TYPE_0.getCode().equals(contacts.getTag())){
                    //新的set中增加旧的成功则为删除
                    contacts.setIsDeleted(true);
                    contacts.setUpdatedAt(new Date());
                    contactsService.updateById(contacts);
                    log.info("删除联系人为：{}", contacts);
                }
            }
        }
    }

    @Override
    public void createSparkOrder(SparkOrderRequest request) {
        Dictionary dictionary = this.mbpOrgMapping(request.getOrgCode());
        WorkOrderHistory history = new WorkOrderHistory();
        String woSeq = workOrderHistoryService.WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId();
        history.setWoSeq(woSeq);
        history.setDeviceId(request.getImei());
        history.setOrderNo(request.getOrderNo() +"S");
        history.setSubsCode(request.getSubsCode());
        history.setWorkSystem(0);
        history.setOrderType(request.getOrderType());
        history.setFromSystem(2);
        history.setHandleStatus(0);
        history.setOperatorBy("时刻助手");
        history.setOrderChannel(2);
        history.setSpId(dictionary.getValue());
        workOrderHistoryService.save(history);
    }

    @Override
    public Integer spark(SparkOrderRequest request) {
        log.info("入参为：{}",request);
        Dictionary dictionary = this.mbpOrgMapping(request.getOrgCode());
        String spId = dictionary.getValue();
        String imei = request.getImei();
        if (request.getImei().contains("-")) {
            imei = request.getImei().split("-")[0];
        }
        Dtu dtu = equipmentService.getDeviceByImei(imei, spId);
        if (dtu == null){
            throw new BizException(request.getImei() + "该设备未在报警器平台注册");
        }
        Integer orderType = 8;
        if( null!=request.getOrderType() && request.getOrderType()>0 ){
            orderType = request.getOrderType();
        }
        LambdaUpdateWrapper<WorkOrderHistory> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(WorkOrderHistory::getDeviceId,imei)
                .eq(WorkOrderHistory::getOrderType, orderType)
                .eq(WorkOrderHistory::getIsDeleted,0).eq(WorkOrderHistory::getOrderNo, request.getOrderNo() +"S");
        log.info("sql为{}", queryWrapper.getSqlSegment());
        WorkOrderHistory history = workOrderHistoryService.getOne(queryWrapper);
        if (request.getState() == 1){
            if (history != null && history.getHandleStatus() == 0){
                throw new BizException(request.getImei() + "该设备已在调试中");
            }else if (history != null && history.getHandleStatus() == 1){
                queryWrapper.set(WorkOrderHistory::getHandleStatus, 0);
                queryWrapper.set(WorkOrderHistory::getReason, null);
                workOrderHistoryService.update(queryWrapper);
                log.info("设备{}调试中1",imei);
                return 1;
            }
            request.setOrderType(orderType);
            this.createSparkOrder(request);
            log.info("设备{}调试中2",imei);
            return 1;
        }else if (request.getState() == 2){
            queryWrapper.set(WorkOrderHistory::getHandleStatus, 1);
            queryWrapper.set(WorkOrderHistory::getReason, "工单中止");
            workOrderHistoryService.update(queryWrapper);
            log.info("设备{}调试结束",imei);
            return 2;
        }
        return -1;
    }

    @Override
    public Integer sparkStatus(SparkOrderRequest request) {
        log.info("sparkStatus入参为：{}",request);
        Dictionary dictionary = this.mbpOrgMapping(request.getOrgCode());
        String spId = dictionary.getValue();
        String imei = request.getImei();
        if (request.getImei().contains("-")) {
            imei = request.getImei().split("-")[0];
        }
        Dtu dtu = equipmentService.getDeviceByImei(imei, spId);
        if (dtu == null){
            throw new BizException(request.getImei() + "该设备未在报警器平台注册");
        }
        Integer orderType = 8;
        if( null!=request.getOrderType() && request.getOrderType()>0 ){
            orderType = request.getOrderType();
        }
        LambdaUpdateWrapper<WorkOrderHistory> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(WorkOrderHistory::getDeviceId,imei)
                .eq(WorkOrderHistory::getOrderType, orderType)
                .eq(WorkOrderHistory::getIsDeleted,0).eq(WorkOrderHistory::getOrderNo, request.getOrderNo() +"S");
        log.info("sql为{}", queryWrapper.getSqlSegment());
        WorkOrderHistory history = workOrderHistoryService.getOne(queryWrapper);
        Integer status = 0;//未开始调试
        if (history != null && history.getHandleStatus() == 0){
            status = 1;//调试中
        }else if(history != null && history.getHandleStatus() == 1){
            status = 2;//调试完成
        }
        return status;
    }

    //获取mbp映射spId
    public Dictionary mbpOrgMapping(String mbpOrgCode) {return dictionaryService.selectValueByAlias(mbpOrgCode); }


//    public void saveConsumerDtu( ConsumerBindingRequest request) {
//        log.info("saveConsumerDtu-request:{}",JSONObject.toJSONString(request));
//        //绑定记录新增
//        ConsumerDtuHistory history = new ConsumerDtuHistory();
//        history.setId(null);
//        history.setBindChannel(Constants.BIND_CHANNEL_MBP);
//        history.setOutOrderCode(request.getOutOrderCode());
//        history.setDeviceId(request.getImei());
//        history.setEvent(1);
//        history.setIMEI(request.getImei());
//        history.setConsumerId(request.getConsumerId());
//        history.setOperationPersonCode("时刻助手销售单");
//        history.setOperationPersonName("asst");
//        history.setRemark(Constants.STR_EMPTY);
//        history.setSpId(request.getSpId());
//        consumerDtuHistoryMapper.insert(history);
//    }

    public  void consumerDtuHistory(String outOrderCode,String imei,String oldImei,Integer event,Integer consumerId,String spId, String industryType) {
        //绑定记录新增
        ConsumerDtuHistory history = new ConsumerDtuHistory();
        history.setId(null);
        history.setBindChannel(2);
        history.setOutOrderCode(outOrderCode);
        history.setDeviceId(imei);
        history.setEvent(event);
        history.setIMEI(imei);
        history.setConsumerId(consumerId);
        history.setOperationPersonCode("时刻助手维修单");
        history.setOperationPersonName("asst");
        history.setRemark(Constants.STR_EMPTY);
        history.setSpId(spId);
        //当没有点型探测器被绑定时
        consumerDtuHistoryMapper.insert(history);
        if (event == 0) {
            consumerServiceInfoService.deleteConsumerServiceInfo(imei);
        } else if (event == 1) {
            consumerServiceInfoService.addConsumerServiceInfo(imei, oldImei, industryType);
        }
    }
}